<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>19根据数据绘制饼图</title>
</head>
<style>
    canvas {
        border: 1px solid #ccc;
    }
</style>
<body>
<canvas width="600" height="400"></canvas>
<script>
    var myCanvas = document.querySelector('canvas');
    var ctx = myCanvas.getContext('2d');
    var w = ctx.canvas.width;
    var h = ctx.canvas.height;
    /*圆心的原点位置*/
    var x0 = w / 2;
    var y0 = h / 2;
    /*圆的半径*/
    var r = 150;
    /*1.根据年龄分布绘制饼图*/
    /*2.准备统计的数据*/

    var data = [5, 25, 10, 5,5];
    /*3.在饼图中表示出来*/
    /*4.把数据转换成弧度*/
    var total = 0;
    var angleList = [];
    for (var i = 0; i < data.length; i++) {
        total += data[i];
    }
    /*获取随机颜色*/
    var getRandomColor = function () {
        var i = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return 'rgb(' + i + ',' + g + ',' + b + ')';
    };
    /*第二次转换成弧度的时候就可以去绘制扇形 减少一次遍历*/
    for (var i = 0; i < data.length; i++) {
        var angle = 2 * Math.PI * (data[i] / total);
        angleList.push(angle);
    }
    /*根据弧度绘制扇形*/
    var startAngle = 0;
    angleList.forEach(function (item, index) {
        /*上一次绘制的结束弧度等于当前次数的起始弧度*/
        var endAngle = startAngle + item;
        ctx.beginPath();
        ctx.moveTo(x0, y0);
        ctx.arc(x0, y0, r, startAngle, endAngle);
        ctx.fillStyle=getRandomColor();
        ctx.fill();
        /*记录当前的结束位置作为下一次的起始位置*/
        startAngle =endAngle;
    })
</script>
</body>
</html>
